package com.gitee.cui.netty.codec;

import com.gitee.cui.util.Logger;
import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.ByteToMessageCodec;

import java.util.List;

/**
 * Byte解码成Integer，Integer编码成Byte的编解码器
 * @author cuiqingqiang
 * @version 1.0
 * @date 2021/10/25 10:52
 **/
public class Byte2IntegerCodec extends ByteToMessageCodec<Integer> {
    @Override
    protected void encode(ChannelHandlerContext ctx, Integer msg, ByteBuf out) throws Exception {
        out.writeInt(msg);
        Logger.info("encoder Integer:" + msg);
    }

    @Override
    protected void decode(ChannelHandlerContext ctx, ByteBuf in, List<Object> out) throws Exception {
        if (in.readableBytes() > 4) {
            int i = in.readInt();
            Logger.info("decoder Integer:" + i);
            out.add(i);
        }
    }
}
